# -*- codin UTF-8 -*-

import pandas as pd
import numpy as np
import matplotlib.pylab as pl
from matplotlib.pylab import rcParams
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima_model import ARIMA
rcParams['figure.figsize'] = 15, 6

def test_stationarity(timeseries):
    
    rolmean = pd.rolling_mean(timeseries, window=12)
    rolstd = pd.rolling_std(timeseries, window=12)

    orig = pl.plot(timeseries, color='blue',label='Original')
    mean = pl.plot(rolmean, color='red', label='Rolling Mean')
    std = pl.plot(rolstd, color='black', label = 'Rolling Std')
    pl.legend(loc='best')
    pl.show()




dateparse = lambda dates: pd.datetime.strptime(dates, '%Y/%m/%d')
data = pd.read_csv('C:/Users/chengk/Desktop/a1.csv', parse_dates='date', index_col='date',date_parser=dateparse)

#test_stationarity(data)

data_log = np.log(data)
moving_avg = pd.rolling_mean(data_log,12)

data_log_moving_avg_diff = data_log - moving_avg
data_log_moving_avg_diff.head(12)
data_log_moving_avg_diff.dropna(inplace=True)
#test_stationarity(data_log_moving_avg_diff)

expwighted_avg = pd.ewma(data_log, halflife=12)

data_log_ewma_diff = data_log - expwighted_avg
#test_stationarity(data_log_ewma_diff)


data_log_diff = data_log - data_log.shift()
data_log_diff.dropna(inplace=True)
#test_stationarity(data_log_diff)



model = ARIMA(data_log, order=(2, 1, 0))  
results_AR = model.fit(disp=-1)  
#pl.plot(data_log_diff)
#pl.plot(results_AR.fittedvalues, color='red')

#pl.show()



predictions_AR_diff = pd.Series(results_AR.fittedvalues, copy=True)
predictions_AR_diff_cumsum = -predictions_AR_diff.cumsum()

predictions_AR_log = pd.Series(data_log.ix[0], index=data_log.index)
predictions_AR_log = predictions_AR_log.add(predictions_AR_diff_cumsum,fill_value=0)
predictions_AR = np.exp(predictions_AR_log+3.5)
pl.plot(data)
pl.plot(predictions_AR)
pl.show()
